package com.nightpiter.model.reader;

import static com.nightpiter.controller.log.Logger.logException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.content.Context;
import android.content.Resources.NotFoundException;

import com.nightpiter.R;
import com.nightpiter.model.MetroModel;
import com.nightpiter.model.MetroModelBuilder;
import com.nightpiter.model.exceptions.BuilderException;
import com.nightpiter.model.exceptions.ModelNotAssignedBuilderException;

/**
 * Model reader interface
 * 
 * implementation have to open file in path and put parsed data in model
 * 
 * changed in r77 by Karkaroff; now both readFromFile and readFromResource
 * methods return builded MetroModel instance
 * 
 * now both methods work only with test XML file, but in future is easy to do
 * path changing
 * 
 * Because of full MVC was implemented, both MetroModelReader's methods return
 * void now
 * 
 * @author Hanhe
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 * 
 */
public abstract class MetroModelReader {

	/**
	 * builder instance
	 */
	protected MetroModelBuilder modelBuilder;

	/**
	 * protected constructor
	 * 
	 * initializes modelBuilder field
	 * 
	 * @throws ModelNotAssignedBuilderException
	 */
	protected MetroModelReader(MetroModel model)
			throws ModelNotAssignedBuilderException {
		modelBuilder = new MetroModelBuilder(model);
	}

	public void readFromFile(String path, Context context)
			throws BuilderException {
		InputStream inputStream = null;

		if (path == null) {
			inputStream = context.getResources().openRawResource(
					R.raw.crazy_piter);
		} else {
			try {
				inputStream = new FileInputStream(path);
			} catch (FileNotFoundException e) {
				logException(e);
			}
		}

		readStream(inputStream);
	}

	public void readFromResource(int resource, Context context)
			throws NotFoundException, BuilderException {
		// opening test XML file in input stream
		InputStream inputStream = context.getResources().openRawResource(
				resource);
		readStream(inputStream);
	}

	protected abstract void readStream(InputStream inputStream)
			throws BuilderException;

}
